package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢忠涵7
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${tencent.map.key}")
    //腾讯地图服务的key
    private String key;
    /**
     * 计算驾驶路线
     */
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //使用 RestTemplate 调用 腾讯位置服务的接口
        //1.封装好Url
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //2.写好映射关系
        Map<String, String> map = new HashMap<>();
        map.put("from", calculateDrivingLineForm.getStartPointLatitude()
                + "," + calculateDrivingLineForm.getStartPointLongitude());
        map.put("to", calculateDrivingLineForm.getEndPointLatitude()
                + "," + calculateDrivingLineForm.getEndPointLongitude());
        map.put("key", key);
        //3.调用
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        //4.根据返回的文档来封装好DrivingLineVo
        if(null == result) {
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        int status = result.getIntValue("status");
        if(status != 0) {
            log.warn("状态说明: {}",result.getJSONObject("message").toString());
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        JSONObject route = result.getJSONObject("result")
                           .getJSONArray("routes")
                           .getJSONObject(0);
        //方案总距离 转换单位为千米并且保留两位小数,并四舍五入
        drivingLineVo.setDistance(route.getBigDecimal("distance").divide(new BigDecimal(1000),2, RoundingMode.HALF_UP));
        //方案估算时间 分钟
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //方案路线坐标点串
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        //返回
        return drivingLineVo;
    }
}
